<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\ApiException;
use App\Exceptions\FormException;
use App\Models\AccountLog;
use App\Models\Order;
use App\Models\User;
use App\Models\UserAccount;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class AccountRechargeController extends Controller
{
    public function index(){
        return view('Admin.accountRecharge.index');
    }

    /**
     * 查询用户信息
     * @name info
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/24 15:47
     */
    public function info(Request $request){
        $payload = $request->only('keyword','userid');
        Validator::make($payload, [
            'keyword'  => 'required_without:userid',
        ],[
            'keyword.required_without'   => '请输入查询内容',
        ])->validate();


        try{
            $keyword = Arr::get($payload,'keyword','');

            $data = User::with(['userAccountInfo', 'userHasOrder'=>function($query){
                //$query->Where('status',Order::STATUS_SUCCESS);
                $query->orderBy('id','desc');
            }, 'provinceInfo', 'cityInfo','inviteUserInfo','inviteUserInfo.userDepartment','inviteUserInfo.userPosition'])
                    ->when($keyword != '',function($query)use($keyword){
                        $query->where(function($query)use($keyword){
                            $query->where('nickname', $keyword)
                                ->orWhere('realname',$keyword)
                                ->orWhere('phone',$keyword)
                                ->orWhere('number',$keyword);
                        });
                    })
                    ->when($user_id = Arr::get($payload,'userid'),function($query)use($user_id){
                        $query->orWhere('id',$user_id);
                    })
                    ->first();
            if(!$data)
                throw new \Exception('未查询到会员');

            $data->surplus_time = $this->surplusTime($data->userAccountInfo); //会员剩余时间
            $data->calcLevel = is_null($data->userAccountInfo) ? '' : $this->calcLevel($data->userAccountInfo); //会员等级
            //$data->user_type_name = is_null($data->user_type) ? '' : ( $data->user_type == 1 ? '员工' : '用户' ); //会员身份
            //$data->department_name = is_null($data->userDepartment) ? '' : $data->userDepartment->department_name;
            $data->sex_name = is_null($data->sex) ? '' : ( $data->sex == 1 ? '男' : '女' ); //性别
            $data->money_consh = is_null($data->userAccountInfo) ? '' : numberFormat($data->userAccountInfo->money_consh,2);
            $data->money_eight_consh = is_null($data->userAccountInfo) ? '' : numberFormat($data->userAccountInfo->money_eight_consh,2);
            $data->money_recharge = is_null($data->userAccountInfo) ? '' : numberFormat($data->userAccountInfo->money_recharge,2);//充值余额
            $userHasOrder = $data->userHasOrder; //关联订单
            $data->order_num = collect($userHasOrder)->count(); //订单数
            $data->total_real_pay = numberFormat(DB::table('order')->where('user_id',$data->id)->where('status',Order::STATUS_SUCCESS)->sum('real_pay')); //交易额
            //查询邀请人数
            $data->user_has_invite_count = User::where([
                ['is_real', '=', '1'],
                ['inviter_user_id', '=', $data->id]
            ])->count();


        }catch (\Exception $exception){

            throw new FormException(App::environment('local') ? $exception->getMessage() : '未查询到会员' );

        }

        return $this->getResponse('查询成功',$data->toArray());
    }

    //计算剩余会员时间
    public function surplusTime($userAccountInfo)
    {
        if(is_null($userAccountInfo) || $userAccountInfo->user_level_id == 1){
            return '';
        }else{
            $surplusTime = DateController::span($userAccountInfo->time_level, time(), 'days,hours,minutes,seconds');
            if($surplusTime['days'] > 0){
                return '剩余' . $surplusTime['days'] . '天';
            }elseif($surplusTime['hours'] > 0){
                return '剩余' . $surplusTime['hours'] . '小时';
            }elseif($surplusTime['minutes'] > 0){
                return '剩余' . $surplusTime['minutes'] . '分钟';
            }elseif($surplusTime['seconds'] > 0){
                return '剩余' . $surplusTime['seconds'] . '秒';
            }
        }
    }


    //拼接会员等级
    public function calcLevel($userAccountInfo)
    {
        if(is_null($userAccountInfo) || is_null($userAccountInfo->user_level_id)){
            return '';
        }else{
            $userLevel = $userAccountInfo->user_level_id;
            return UserAccount::LEVEL[$userLevel];
        }
    }

    /**
     * 充值
     * @name recharge
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/31 13:49
     */
    public function recharge(Request $request,$id){
        $payload = $request->only(['recharge_value','recharge_type']);
        Validator::make($payload, [
            'recharge_value'  => 'required|numeric',
            'recharge_type'  => 'required|in:money_recharge,money_eight_consh,money_consh',
        ],[
            'recharge_value.required'   => '请输入充值金额',
            'recharge_value.numeric'   => '请输入充值金额',
            'recharge_type.required'   => '请选择充值类型',
            'recharge_type.in'   => '请选择充值类型',
        ])->validate();

        try{
            DB::beginTransaction();

            $account = UserAccount::where('user_id',$id)->sharedLock()->first();

            if(!$account)
                throw new ApiException('账户未授权');

            /* 修改账户表 */
            $field = $payload['recharge_type'];
            $account->$field += $payload['recharge_value'];
            $totalField = UserAccount::TOTAL_FIELD[$field];
            $account->$totalField += $payload['recharge_value'];

            /* 修改用户重置次数 */
            if($payload['recharge_type'] == 'money_recharge'){
                $account->success_recharge++;
            }
            $account->save();

            /* 充值日志记录 */
            $accountLog = new AccountLog();
            $accountLog->user_id = $id;
            $accountLog->account_type = AccountLog::ACCOUNT_TYPE_VALUE[$payload['recharge_type']];
            $accountLog->money = $payload['recharge_value'];
            $accountLog->balance = $account->$field;
            $accountLog->type = AccountLog::ADMIN_RECHARGE_TYPE;
            $accountLog->status = AccountLog::SUCCESS;
            $accountLog->remark = '后台充值';
            $accountLog->created_at = Carbon::now()->toDateTimeString();
            $accountLog->save();

            /* 清楚前端缓存 */
            Cache::store('redis')->forget('user:info_' . $id);


            DB::commit();
        }catch (ApiException $exception){

            DB::rollBack();
            throw new FormException($exception->getMessage());


        }catch (\Exception $exception){

            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '充值失败' );

        }

        return $this->getResponse('充值成功');

    }
}
